<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择特种作业人员"
    width="800px"
    @close="handleClose"
  >
    <div class="personnel-select">
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-select v-model="filters.type" placeholder="选择工种" @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="电工" value="electrician" />
              <el-option label="焊工" value="welder" />
              <el-option label="起重工" value="crane_operator" />
              <el-option label="高空作业" value="high_altitude" />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select v-model="filters.department" placeholder="选择部门" @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="维修部" value="maintenance" />
              <el-option label="生产部" value="production" />
              <el-option label="安全部" value="safety" />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-input
              v-model="filters.keyword"
              placeholder="搜索姓名或工号"
              @input="handleFilter"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
        </el-row>
      </div>
      
      <!-- 人员列表 -->
      <div class="personnel-list">
        <el-table
          :data="filteredPersonnel"
          @selection-change="handleSelectionChange"
          max-height="400"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="employeeId" label="工号" width="100" />
          <el-table-column prop="type" label="工种" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ getTypeLabel(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="department" label="部门" width="120" />
          <el-table-column prop="certificateNumber" label="证书编号" width="150" />
          <el-table-column prop="certificateExpiry" label="证书有效期" width="120">
            <template #default="{ row }">
              <span :class="{ 'expired': isExpired(row.certificateExpiry) }">
                {{ row.certificateExpiry }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === 'available' ? 'success' : 'danger'" size="small">
                {{ row.status === 'available' ? '可用' : '不可用' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 已选择人员 -->
      <div v-if="selectedPersonnel.length > 0" class="selected-section">
        <h4>已选择人员 ({{ selectedPersonnel.length }})</h4>
        <div class="selected-list">
          <el-tag
            v-for="person in selectedPersonnel"
            :key="person.id"
            closable
            @close="removeSelected(person.id)"
            style="margin-right: 8px; margin-bottom: 8px"
          >
            {{ person.name }} ({{ getTypeLabel(person.type) }})
          </el-tag>
        </div>
      </div>
    </div>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :disabled="selectedPersonnel.length === 0">
        确定 ({{ selectedPersonnel.length }})
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

interface Personnel {
  id: string
  name: string
  employeeId: string
  type: string
  department: string
  certificateNumber: string
  certificateExpiry: string
  status: 'available' | 'unavailable'
}

interface Props {
  modelValue: boolean
  personnelTypes?: string[]
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'confirm', personnel: Personnel[]): void
}

const props = withDefaults(defineProps<Props>(), {
  personnelTypes: () => []
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const filters = reactive({
  type: '',
  department: '',
  keyword: ''
})

const selectedPersonnel = ref<Personnel[]>([])

// 模拟人员数据（持证人员库）
const personnelData: Personnel[] = [
  {
    id: '1',
    name: '张三',
    employeeId: 'E001',
    type: 'electrician',
    department: '维修部',
    certificateNumber: 'EC2023001',
    certificateExpiry: '2025-12-31',
    status: 'available'
  },
  {
    id: '2',
    name: '李四',
    employeeId: 'E002',
    type: 'welder',
    department: '维修部',
    certificateNumber: 'WC2023001',
    certificateExpiry: '2025-10-15',
    status: 'available'
  },
  {
    id: '3',
    name: '王五',
    employeeId: 'E003',
    type: 'crane_operator',
    department: '生产部',
    certificateNumber: 'CO2023001',
    certificateExpiry: '2023-12-31',
    status: 'unavailable'
  },
  {
    id: '4',
    name: '赵六',
    employeeId: 'E004',
    type: 'high_altitude',
    department: '维修部',
    certificateNumber: 'HA2023001',
    certificateExpiry: '2025-08-20',
    status: 'available'
  },
  {
    id: '5',
    name: '钱七',
    employeeId: 'E005',
    type: 'electrician',
    department: '生产部',
    certificateNumber: 'EC2023002',
    certificateExpiry: '2025-11-30',
    status: 'available'
  },
  {
    id: '6',
    name: '孙八',
    employeeId: 'E006',
    type: 'pressure_vessel',
    department: '工程部',
    certificateNumber: 'PV2023001',
    certificateExpiry: '2025-09-15',
    status: 'available'
  },
  {
    id: '7',
    name: '周九',
    employeeId: 'E007',
    type: 'welder',
    department: '生产部',
    certificateNumber: 'WC2023002',
    certificateExpiry: '2025-07-30',
    status: 'available'
  }
]

// 过滤后的人员列表
const filteredPersonnel = computed(() => {
  let result = personnelData

  // 根据选择的工种类型过滤
  if (props.personnelTypes.length > 0) {
    result = result.filter(person => props.personnelTypes.includes(person.type))
  }

  // 根据筛选条件过滤
  if (filters.type) {
    result = result.filter(person => person.type === filters.type)
  }

  if (filters.department) {
    result = result.filter(person => person.department === filters.department)
  }

  if (filters.keyword) {
    const keyword = filters.keyword.toLowerCase()
    result = result.filter(person => 
      person.name.toLowerCase().includes(keyword) ||
      person.employeeId.toLowerCase().includes(keyword)
    )
  }

  return result
})

// 获取工种标签
const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    electrician: '电工',
    welder: '焊工',
    crane_operator: '起重工',
    high_altitude: '高空作业',
    pressure_vessel: '压力容器'
  }
  return typeMap[type] || type
}

// 检查证书是否过期
const isExpired = (expiryDate: string) => {
  const today = new Date()
  const expiry = new Date(expiryDate)
  return expiry < today
}

// 处理筛选
const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

// 处理选择变化
const handleSelectionChange = (selection: Personnel[]) => {
  selectedPersonnel.value = selection
}

// 移除已选择的人员
const removeSelected = (id: string) => {
  selectedPersonnel.value = selectedPersonnel.value.filter(person => person.id !== id)
}

// 确认选择
const handleConfirm = () => {
  if (selectedPersonnel.value.length === 0) {
    ElMessage.warning('请至少选择一名人员')
    return
  }

  // 检查是否有证书过期的人员
  const expiredPersonnel = selectedPersonnel.value.filter(person => 
    isExpired(person.certificateExpiry)
  )

  if (expiredPersonnel.length > 0) {
    ElMessage.warning('所选人员中有证书已过期，请重新选择')
    return
  }

  // 转换为符合纸质版许可证格式的数据
  const formattedPersonnel = selectedPersonnel.value.map(person => ({
    name: person.name,
    certificateNumber: person.certificateNumber,
    certificateName: getTypeLabel(person.type) + '证',
    validityPeriod: person.certificateExpiry
  }))

  emit('confirm', formattedPersonnel)
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  selectedPersonnel.value = []
  filters.type = ''
  filters.department = ''
  filters.keyword = ''
}

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (visible) {
    selectedPersonnel.value = []
  }
})
</script>

<style lang="scss" scoped>
.personnel-select {
  .filter-section {
    margin-bottom: 20px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 4px;
  }
  
  .personnel-list {
    margin-bottom: 20px;
    
    .expired {
      color: #f56c6c;
      font-weight: 500;
    }
  }
  
  .selected-section {
    h4 {
      color: #333;
      margin-bottom: 12px;
    }
    
    .selected-list {
      min-height: 40px;
      padding: 12px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      background: #f8f9fa;
    }
  }
}
</style>
